/**
 * 
 */
package cc.dogtailflower.framework.handler;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cc.dogtailflower.framework.annotation.RequestMapping;
import cc.dogtailflower.framework.bean.Request;
import cc.dogtailflower.framework.bean.RequestBean;
import cc.dogtailflower.framework.constant.RequestMethod;
import cc.dogtailflower.framework.util.ArrayUtil;
import cc.dogtailflower.framework.util.CollectionUtil;

/**
 * Controller处理类
 * 
 * @author cc
 *
 */
public class ControllerHandler {

	/*
	 * 请求与处理器之间的映射集合
	 */
	private static final Map<Request,RequestBean> REQUEST_MAP = new HashMap<Request,RequestBean>();
	
	static{
		Set<Class<?>> controllerClassSet = ClassHandler.getControllerClassSet();
		if(CollectionUtil.isNotEmpty(controllerClassSet)){
			for(Class<?> controllerClass : controllerClassSet){
				Method[] methods = controllerClass.getDeclaredMethods();
				if(ArrayUtil.isNotEmpty(methods)){
					for(Method method : methods){
						//判断当前方法是否带有 @RequestMapping注解
						if(method.isAnnotationPresent(RequestMapping.class)){
							RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
							String requestPath = requestMapping.value();
							RequestMethod requestMethod = requestMapping.method();
							Request request = new Request(requestMethod,requestPath);
							RequestBean requestHandler = new RequestBean(controllerClass,method);
							REQUEST_MAP.put(request, requestHandler);
						}
					}
				}
			}
		}
	}
	
	/*
	 * 获取 RequestHandler
	 */
	public static RequestBean getRquestHandler(String requestPath,RequestMethod requestMethod){
		Request request = new Request(requestMethod,requestPath);
		return REQUEST_MAP.get(request);
		
	}
}
